const http=require("http");
const fs=require("fs");

var userList=[];

function getData(str){
    var arr=str.split("&");
    var obj={}
    for(var i=0;i<arr.length;i++){
        var childArr=arr[i].split("=");
        obj[childArr[0]]=childArr[1];
    }
    return obj;
}

http.createServer((req,res)=>{
    var urlObj=new URL(req.url,"http://localhost:8081/");
    var pathName=urlObj.pathname;
    if(pathName == '/'){
        var fileContent=fs.readFileSync('./post.html')
        res.writeHead(200,{"Content-Type":"text/html;charset=utf8"});
        res.write(fileContent)
        res.end()
    }
    else if(pathName =='/save'){
        var str='';
        req.on("data",(chunk)=>{
            str+=chunk;
        })
        req.on("end",()=>{
            var postObj=getData(str);
            userList.push(postObj);
            res.end("submit success");
        })
    }
    else if(pathName=='/list'){
        var fileContent=fs.readFileSync("./list.html");
        res.writeHead(200,{"Content-Type":"text/html;charset=utf-8"});
        res.write(fileContent);
        res.end()
    }   
    else if(pathName =='/getlist'){
        var userStr =JSON.stringify(userList);
        res.writeHead(200,{"Content-Type":"text/plain"});
        res.end(userStr)
    }else if(pathName =='/del'){
        var delUser=urlObj.searchParams.get('deluser');
        for(var i=0;i<userList.length;i++){
            if(userList[i]["username"]==delUser){
                userList.splice(i,1);
                res.end('delete success');
                return;
            }
        }
    }

}).listen(8081);